//
//  WLoginViewController.swift
//  iiatn
//
//  Created by mnine on 18/4/1.
//  Copyright © 2018年 mnine. All rights reserved.
//

import UIKit
import SVProgressHUD
import Alamofire
import SwiftyJSON
import SwiftKeychainWrapper


//创建协议
protocol GetCancelMessageDelegate:NSObjectProtocol
{
    //回调方法 传一个String类型的值
    func getCancelMessage()
}
class WLoginViewController: UIViewController {

    // phone or email
    @IBOutlet weak var username: UITextField!
    
    @IBOutlet weak var password: UITextField!
    
    @IBOutlet weak var loginbtn: UIButton!
    
    @IBOutlet weak var forgetbtn: UIButton!
    
    @IBOutlet weak var registerbtn: UIButton!
    

    var wperson : WPerson?
    
    var tag = false
    
    var delegate:GetCancelMessageDelegate?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 设置导航栏的左右按钮
        setupBarButtonItem()
        setupBtnStyle()
        setupdosth()

    }
    func setupdosth(){
        loginbtn.addTarget(self, action: #selector(trylogin), for: .touchUpInside)
        registerbtn.addTarget(self, action: #selector(toRegister), for: .touchUpInside)
        forgetbtn.addTarget(self, action: #selector(pForget), for: .touchUpInside)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    // MARK: - 设置导航栏按钮
    private func setupBarButtonItem() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .plain, target: self, action:
            #selector(cancelButtonClick))
    }

    // MARK: - 设置按钮风格
    private func setupBtnStyle() {
        
        loginbtn.x = SCREENW/2 - loginbtn.width/2
        registerbtn.x = SCREENW/2 - registerbtn.width/2
        username.x = SCREENW/2 - username.width/2
        password.x = SCREENW/2 - password.width/2
        forgetbtn.x = SCREENW/2 - forgetbtn.width/2
        
        password.isSecureTextEntry = true
        
        loginbtn.layer.cornerRadius = loginbtn.height * 0.25
        loginbtn.layer.masksToBounds = true
        loginbtn.layer.rasterizationScale = UIScreen.main.scale
        loginbtn.layer.shouldRasterize = true
        registerbtn.layer.cornerRadius = registerbtn.height * 0.25
        registerbtn.layer.masksToBounds = true
        registerbtn.layer.rasterizationScale = UIScreen.main.scale
        registerbtn.layer.shouldRasterize = true
        registerbtn.layer.borderWidth = 0.5
        registerbtn.layer.borderColor = UIColor.red.cgColor
        username.layer.borderWidth = 0.8
        username.layer.borderColor = UIColor.gray.cgColor
        username.layer.cornerRadius = loginbtn.height * 0.2
        username.layer.masksToBounds = true
        password.layer.cornerRadius = loginbtn.height * 0.2
        password.layer.masksToBounds = true
        password.layer.borderWidth = 0.8
        password.layer.borderColor = UIColor.gray.cgColor
    }
    
    func trylogin(){
        
        if(username.text!.isEmpty){
            SVProgressHUD.showError(withStatus: "账号不能为空！")
        }else if(password.text!.isEmpty){
            SVProgressHUD.showError(withStatus: "密码不能为空！")
        }else{
            Alamofire
                .request(BASE_URL + "apin/user/login/\(username.text!)/\(password.text!)")
                .responseJSON { (response) in
                    guard response.result.isSuccess else {
                        SVProgressHUD.showError(withStatus: "登录失败...")
                        return
                    }
                    if let value = response.result.value {
                        let dict = JSON(value)
                        let status = dict["status"].intValue
                        let msg = dict["msg"].stringValue
                        print(msg,status)
                        SVProgressHUD.showInfo(withStatus: msg)
                        //let data1 = JSON
                        if status == 1 {
                            let data = JSON(dict["data"].dictionary!)
                            
                            wuserid = data["id"].intValue
                            wphone = data["phone"].stringValue
                            wname = data["name"].stringValue
                            wemail = data["email"].stringValue
                            wprovince = data["province"].stringValue
                            wcity = data["city"].stringValue
                            waddress = data["address"].stringValue
                            wcompany_name = data["company_name"].stringValue
                            NotificationCenter.default.post(name:notifyNameMsgRecv, object: nil, userInfo: nil)
                            whaslogin = true
                            self.rememberlogin()
                            self.dismiss(animated: true, completion: nil)
                        }
                    }
            }
            //WNetwork.shareNetworkTool.tryLogin(username: username.text!, password: password.text!)
        }
        
    }
    func cancelButtonClick() {
        dismiss(animated: true, completion: nil)
        if tag {
            delegate?.getCancelMessage()
            print("地图全览项目登录取消直接返回")
        }
    }
    func toRegister(){
        let VC = WRegisterViewController()
        VC.title = "手机注册"
        let nav = WNavigationController(rootViewController: VC)
        present(nav, animated: true, completion: nil)
    }
    func pForget(){
        let VC = WRegisterViewController()
        VC.title = "忘记密码[手机]"
        let nav = WNavigationController(rootViewController: VC)
        present(nav, animated: true, completion: nil)
    }    
    func rememberlogin(){
        let saveSuccessful:Bool=KeychainWrapper.standard.set(username.text!, forKey:"rusername")
        KeychainWrapper.standard.set(wname!, forKey:"rname")
        KeychainWrapper.standard.set(wuserid!, forKey:"ruserid")
        KeychainWrapper.standard.set(true, forKey:"rloginsuccess")
        print("存储账号",saveSuccessful)
    }
}
